<?php

if (!defined('IN_XLP')) {
	exit('Access Denied!');
}

/**
 * Description of OrderModel
 *
 * @author skyinter
 */
class orderModel extends Model {

	
	
	function __construct() {
		parent::__construct();
		$this->dbTable = 'order';
		$this->page = 20;
	}


	/**
	 * 新增数据
	 * @param   $data array
	 * @return  $result int 
	 */
	public function add($data){
		$result = $this->insert($data);
		return $result;
	}

	/**
	 * 标志位删除
	 * @param   $id int 表主键ID
	 * @return  $result int 
	 */
	public function del($id){
		$data   = '`is_del` = 1';
		$where  = '`id` = '. $id;
		$result = $this->update($data, $where);
		return $result;
	}

	/**
	 * 获取列表数据
	 * @param   $page int 分页数据，默认是第一页
	 * @return  $result array 返回查询数组
	 */
	public function get_list($page = 1, $where = '1 = 1'){
		$result	= $this->page($page, $this->page)->where($where)->order('id desc')->findAll();
		return $result;
	}

	/**
	 * 获取指定ID的数据信息
	 * @param   $id int 表主键ID
	 * @return  $result array
	 */
	public function info($id, $field='*'){
		$result	= $this->field($field)->where('`id` = '. $id)->find();
		return $result;
	}

	public function getOrderByOutSn($out_sn, $field='*') {
		$result = $this->field($field)->where('`order_sn` = '.$out_sn)->find();
		return $result;
	}

	/**
	 * 更新数据
	 * @param   $id int 主键ID
	 * @param   $data array 对应数据字段名称的数组数据
	 * @return  $result int 更新影响记录的数量
	 */
	public function modify($id, $data){
		$where  = '`id` = '.$id;
		$result = $this->update($data, $where);
		return $result;
	}

	/**
	 * 真实删除数据
	 * @param   $id int 主键ID
	 * @return  int 影响记录的数量
	 */
	private function realdel($id){
		$where  = array('id' => $id);
		$result = $this->delete($where);
		return $result;
	}


	public function orderStateConvert($state) {
		$state = intval($state);
		switch ($state) {
			case  0:
				$result = '已取消';
				break;
			case 10:
				$result = '未付款';
				break;
			case 20:
				$result = '已付款';
				break;
			case 30:
				$result = '已处理';
				break;
			case 40:
				$result = '已发货';
				break;
			case 50:
				$result = '已收货';
				break;
			case 60:
			case 62:
			case 63:
				$result = '退款已提交';
				break;
			case 61:
			case 64:
			case 65:
				$result = '退款退货已提交';
				break;
			case 70:
				$result = '退款已处理';
				break;
			case 71:
				$result = '退款退货已处理';
				break;
			default:
				$result = 'unknown';
				break;
		}

		return $result;
	}

	/**
	 * 单商品订单列表
	 * @param  int $uid 用户ID
	 * @return array	订单列表
	 */
	public function orderList($uid) {
		$uid = intval($uid);
		$sql = "SELECT o.`id`,o.`order_sn`,o.`create_time`,o.`order_state`,o.`order_amount`,g.`goods_image`,g.`goods_name`
				FROM __PRE__order o,__PRE__order_goods og,__PRE__goods g
				WHERE o.`id`=og.`order_id`
				AND og.`goods_id`=g.`id`
				AND o.`user_id`=$uid
				ORDER BY o.`create_time` DESC";
		$result = M('order')->query($sql);
		
		if(count($result)) {
			foreach ($result as $k=>$v) {
				$result[$k]['order_state'] = $this->orderStateConvert($v['order_state']);
			}
		}
		
		return $result;
	}

	/*
	 * 调用微信发货接口
	 */
	public function wxDelivery($order_id, $deliver_msg="ok") {
		//订单信息
		$order_info = $this->info($order_id, '`order_sn`,`openid`,`transid`');
		//发送通知
		$result = D('weixin')->delivery($order_info['openid'], $order_info['order_sn'], $order_info['transid'], $deliver_msg);
		return $result;
	}


	/**
	 * 发货
	 * @param  int    $order_id             订单ID
	 * @param  int 	  $shipping_express_id 快递公司ID
	 * @param  string $shipping_code       物流单号
	 */
	public function deliver($order_id, $shipping_express_id, $shipping_code) {
		$data = array(
			'shipping_code' 		=> $shipping_code,
			'shipping_express_id'	=> $shipping_express_id,
			'order_state'			=> 40,	//发货状态
		);

		//通知微信发货成功 也可以发送ok之外的信息 如缺货不发等
		$wx_result = $this->wxDelivery($order_id, 'ok');
		$wx_result = json_decode($wx_result, true);
		
		if($wx_result['errcode'] == 0) {
			//更新订单状态
			M('order')->update($data, array('id' => $order_id));
			//日志
			$this->log($order_id, 40, '', 'admin-'.admin::$adminInfo['id']);

			return true;
		} else {
			return false;
		}
	}


	/**
	 * 取消订单
	 * @param  int 	  $order_id 订单ID
	 * @param  string $note     取消原因备注
	 */
	public function cancel($order_id, $note) {

		//修改订单状态
		$result = M('order')->update(array('order_state'=>0 , 'remark' => $note ,'cancel_time' => TIME),array('id'=>$order_id));
		
		return $result ? true : false;
	}


	/*
	 * 解冻结邻币
	 */
	public function score_unfreeze($order_id) {

		$order_info = $this->info($order_id, '`order_sn`,`score_used`,`user_id`');

		if(empty($order_info)) {
			return false;
		}

		if( $order_info['score_used'] <= 0 ) {
			return true;
		}

		$data['uid']      = $order_info['user_id'];
        $data['act']	  = 1;
        $data['credit']	  = intval($order_info['score_used']);
        $data['content']  = '取消订单解冻结邻币 订单号：'.$order_info['order_sn'];
		$data['infotime'] = TIME;

		M('user')->where(array('uid' => $data['uid']))->setInc('shopping_credit', $data['credit']);

		//积分日志
		if (M('shopping_credit_log')->insert($data)) {
			return true;
		} else {
			return false;
		}

	}

	/*
	 * 取消订单 还原库存
	 */
	public function restore_stock($order_id) {
		$rs = D('orderGoods')->getOrderGoods($order_id,'`goods_id`,`goods_num`');
		if($rs) {
			foreach ($rs as $k => $v) {
				$result = M('goods')->field('`is_sale_down`')->where(array('id'=>$v['goods_id']))->find();
				if($result['is_sale_down']) {
					M('goods')->update(
						"`storage_number`=`storage_number`+{$v['goods_num']}, `sale_count`=`sale_count`-{$v['goods_num']}",
						array('id'=>$v['goods_id'])
					);
				} else {
					M('goods')->update(
						"`storage_number`=`storage_number`+{$v['goods_num']}",
						array('id'=>$v['goods_id'])
					);
				}
			}
		}
		return true;
	}

	/**
	 * 确认收货
	 * @param  int 	  $order_id 订单ID
	 * @param  string $note     备注
	 * @param  string $operator 操作人
	 */
	public function received($order_id, $note, $operator) {
		//修改订单状态
		$result = M('order')->update(
			array('order_state'=>50, 'finish_time'=>time()),
			array('id'=>$order_id)
		);
		//日志
		$this->log($order_id, 50, $note, $operator);
		return $result;
	}

	/**
	 * 用户申请退款
	 * @param  int 		$order_id      订单ID
	 * @param  array 	$refund_goods  退款商品ID array(1,2,3,...)
	 * @param  string 	$note          退款原因
	 * @return boolean                 操作状态
	 */
	public function refund($order_id, $refund_goods, $note) {
		
		$order_info = M('order')
			->field('`id`,`order_sn`,`user_id`,`recipients`,`order_state`,`order_amount`')
			->where(array('id'=>$order_id))
			->find();

		//检查用户
		if($order_info['user_id'] != user::$userInfo['uid']) {
			showError('非法访问');
		}
		//检查订单状态
		if( !in_array($order_info['order_state'], array(20,30,40)) ) {	//已付款OR已处理OR已发货状态
			showError('非法提交');
		}

		//更新商品退款金额 每件商品默认退全款
		$ids = implode(',', $refund_goods);
		$goods = M('order_goods')->field('`id`,`goods_num`,`goods_price`')->where("`id` in ($ids)")->findAll();

		$total_refund_amount = 0;	//退款总额
		foreach ($goods as $v) {
			//更新商品退款金额
			$refund_amount = $v['goods_num']*$v['goods_price'];
			M('order_goods')->update(
				array('goods_refund' => $refund_amount),
				array('id' => $v['id'])
			);
			$total_refund_amount += $refund_amount;
		}

		//修改订单状态
		$result = M('order')->update(
			array(
				'order_state'   => 60,
				'refund_time'   => time(),
				'refund_amount' => $total_refund_amount,
				'refund_state'  => 1,		//退款申请已提交
			),
			array('id'=>$order_id)
		);

		//添加退款log
		M('return_log')->insert(array(
			'order_id'     => $order_info['id'],
			'order_sn'     => $order_info['order_sn'],
			'user_id'      => $order_info['user_id'],
			'recipient'    => $order_info['recipients'],
			'order_amount' => $order_info['order_amount'],
			'order_refund' => $total_refund_amount,
			'return_msg'   => $note,
			'return_time'  => time(),
		));

		//日志
		$this->log($order_id, 60, $note, 'user-'.user::$userInfo['uid']);
		return $result;
	}


	/**
	 * 用户申请退款退货
	 * @param  int 	  $order_id     订单ID
	 * @param  array  $return_goods 退货商品ID和数量 array('id'=>'num',...)
	 * @param  string $note         退货原因
	 * @return boolean              操作状态
	 */
	public function return_goods($order_id, $return_goods, $note) {

		$order_info = M('order')
			->field('`id`,`order_sn`,`user_id`,`recipients`,`order_state`,`order_amount`')
			->where(array('id'=>$order_id))
			->find();

		//检查用户
		if($order_info['user_id'] != user::$userInfo['uid']) {
			showError('非法访问');
		}
		//检查订单状态
		if($order_info['order_state'] != 40) {	//已发货状态
			showError('非法提交');
		}

		//更新商品退款和退货金额 每件商品按退货数量退款
		$ids = '';
		foreach ($return_goods as $k => $v) {
			$ids .= $k.',';
		}
		$ids = rtrim($ids, ',');

		$goods = M('order_goods')->field('`id`,`goods_num`,`goods_price`')->where("`id` in ($ids)")->findAll();

		$total_refund_amount = 0;	//退款总额
		$total_return_amount = 0;	//退货总数

		foreach ($goods as $v) {
			$return_num    = $return_goods[$v['id']];	//退货数量
			$refund_amount = $return_num*$v['goods_price'];	//退款金额
			//更新商品退款金额和退货数量
			M('order_goods')->update(
				array('goods_refund' => $refund_amount, 'goods_returnnum' => $return_num),
				array('id' => $v['id'])
			);

			$total_refund_amount += $refund_amount;
			$total_return_amount += $return_num;
		}

		//修改订单状态
		$result = M('order')->update(array('order_state'=>61),array('id'=>$order_id));
		//修改订单状态
		$result = M('order')->update(
			array(
				'order_state'   => 61,
				'refund_time'   => time(),
				'refund_amount' => $total_refund_amount,	//退款金额
				'return_amount' => $total_return_amount,	//退货数量
				'return_state'  => 1,		//退款退货申请已提交
			),
			array('id'=>$order_id)
		);

		//添加退货log
		M('return_log')->insert(array(
			'order_id'     => $order_info['id'],
			'order_sn'     => $order_info['order_sn'],
			'user_id'      => $order_info['user_id'],
			'recipient'    => $order_info['recipients'],
			'order_amount' => $order_info['order_amount'],
			'order_refund' => $total_refund_amount,
			'order_return' => $total_return_amount,
			'return_msg'   => $note,
			'return_time'  => time(),
		));

		//日志
		$this->log($order_id, 61, $note, 'user-'.user::$userInfo['uid']);
		return $result;
	}

	/**
	 * 订单日志
	 * @param  int 	   $order_id    订单ID
	 * @param  int     $order_state 订单目前状态
	 * @param  string  $note        操作备注
	 * @param  string  $operator    管理员/买家ID/system/微信服务器
	 * @return boolean              操作是否成功
	 */
	public function log($order_id, $order_state, $note, $operator) {

		$note = mb_substr($note, 0, 200, 'UTF-8');
		//订单状态
		$order_state_code = $order_state;
		$order_state = $this->orderStateConvert($order_state);

		$result = M('order_log')->insert(array(
			'order_id'		   => $order_id,
			'order_state_code' => $order_state_code,
			'order_state' 	   => $order_state,
			'note'		  	   => $note,
			'log_time'		   => time(),
			'operator'	  	   => $operator,
		));

		return $result ? true : false;
	}


	/**
	 * 利息记录
	 * @param  int 	   $order_id    订单ID
	 * @return boolean              操作是否成功
	 */
	public function addInterestRecord($order_id) {
		$map ['id'] = $order_id;
		$orderInfo = $this->field("`amount`,user_id")->where($map)->find();
		if(!isHave($orderInfo)) {
			return false;
		}
		$totalMoney = intval($orderInfo['amount']);
		$numberArray = array(
				1 => '01期',
				2 => '02期', 	
				3 => '03期', 	
				4 => '04期', 	
				5 => '05期', 	
				6 => '06期', 	
				7 => '07期', 	
				8 => '08期', 	
				9 => '09期', 	
				10 => '10期'
		);
		$user_level = M('user')->field("`user_level`")->where(array('uid' => $orderInfo['user_id']))->find();
		$level = $user_level['user_level'];
		$setting = F('weixin/setting'); //获取利率配置
		$basic_setting = $setting['basic_setting'];

		if($level == 10) { //黄金会员
			$rate = $basic_setting['gold_rate'];
		}else{
			$rate = $basic_setting['common_rate'];
		}

		$every_interest = $totalMoney * ($rate/100); //计算每期利息
		$todayTime = strtotime(date('Y-m-d'));
		$dueTime = $todayTime + 30*86400 + 86399; //还款截止日期
		$tempTime = $todayTime;
		//循环插入利息表
		for ($i=0; $i < count($numberArray); $i++) { 
			$data = array();
			$data ['order_id'] = $order_id;
			if($i == 9) { //最后一期本金+利息
				$data['payment'] = $totalMoney + $every_interest*3;
			}else{
				$data ['payment']  = $every_interest*3;
			}
			$data ['number']   = $numberArray[$i+1];
			$data ['node_time'] = $tempTime;
			$tempTime = $tempTime + 3*86400;
			//头期利息默认扣除
			if( $i == 0) {
				$data['status'] = 20;
				$data['finish_time'] = TIME;
			}
			M('order_interest')->insert($data);
		}
		$this->update(array('due_time' => $dueTime,'confirm_time' => TIME) , array('id' => $order_id));
		return true;
	}
	
}